package com.baizhi.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLIBProxyUtil {

    private Actor actor ;



    public Actor getProxy(final Actor actor){
     this.actor = actor;


        //新建增强器
        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(actor.getClass());

        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                System.out.println("检查是否预约");

                if(method.getName().equals("dance")){
                    System.out.println("给多少钱都不跳舞");
                    return null;
                }

                Actor ac = (Actor) method.invoke(actor, objects);

                if(method.getName().equals("eat")){
                    System.out.println("记录以下，某年某月某日"+ actor.getName() + "和某男子一起吃饭");
                }else if(method.getName().equals("sing")){
                    System.out.println("记录以下，某年某月某日"+ actor.getName() + "和某男子一起唱歌");
                }

                return ac;
            }
        });

        return (Actor) enhancer.create();
    }
}
